package ar.utn.jess.servlet;

import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

public class Login extends BaseServlet {

	private static final long serialVersionUID = 1L;
	

	protected void serve(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
		
		if(req.getParameter("debug")!=null) {
			// muestra un pagina con los parametros recibidos
			req.setAttribute("paramsMap", paramsToCustomMap(req));
			
			RequestDispatcher rd = getServletContext().getRequestDispatcher("/WEB-INF/pages/defaultResponse.jsp");		
			rd.forward(req, resp);
		}
		else {
			// genera respuesta en formato json con los parametros recibidos			
			Gson gson = new Gson();
			
			Map<String, String> result = paramsToCustomMap(req);
			result.put("connection", "OK");
			
			resp.setContentType("application/json;charset=utf-8");
			resp.getWriter().write(gson.toJson(result));
		}		
	}
	
	@SuppressWarnings("rawtypes")
	private Map<String, String> paramsToCustomMap(HttpServletRequest req) {
		
		Map<String, String> result = new HashMap<String, String>();
		
		Enumeration en = req.getParameterNames();
	        
        while (en.hasMoreElements()) {
            
            String paramName = (String) en.nextElement();
            result.put(paramName, req.getParameter(paramName));
        }
		
		return result;
	}
}
